package com.sky.autofillaspect;

import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;
import java.time.LocalDateTime;


@Aspect
@Component
@Slf4j
public class AutoFill {
    //以注解形式选择切面
    //通知形式：前置通知
    @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.AutoFill)")
    //切入点方法
    public void autoFill(JoinPoint joinPoint) {
        //拿到方法签名可以拿到方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //拿到方法
        Method method = signature.getMethod();
        //拿到形参获取形参对象
        Object[] args = joinPoint.getArgs();


        //根据情况只需要一个参数
        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];
        //获取注解，拿到注解的属性，判断需要增强的字段
        OperationType value = method.getAnnotation(com.sky.anno.AutoFill.class).value();
        try {
            if (value.equals(OperationType.INSERT)) {
                //如果是OperationType.INSERT，则增强以下字段


                Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                Method setCreateUser = arg.getClass().getDeclaredMethod("setCreateUser", Long.class);
                setCreateTime.invoke(arg, LocalDateTime.now());
                setUpdateTime.invoke(arg, LocalDateTime.now());
                setUpdateUser.invoke(arg, BaseContext.getCurrentId());
                setCreateUser.invoke(arg, BaseContext.getCurrentId());

            } else {
                Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateTime.invoke(arg, LocalDateTime.now());
                setUpdateUser.invoke(arg, BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            throw new BaseException("公共字段填充异常");
        }

    }
}
